//
//  MSBusinessUploadInfoController.m
//  MSJD
//
//  Created by 刘律宏 on 2019/4/8.
//  Copyright © 2019年 xiangbo. All rights reserved.
//

#import "MSBusinessUploadInfoController.h"

#import "TZImagePickerController.h"

#import "MSUserCenterDataSource.h"
#import "MSUploadImageUtils.h"

/** 商家入驻界面的选择图片按钮的默认tag值 */
NSInteger const kBusinessIconButtonDefaultTag = 100000000;

@interface MSBusinessUploadInfoController ()<UITextFieldDelegate, TZImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet UITextField *adreessTextField;
@property (weak, nonatomic) IBOutlet UITextField *titleTextField;

@property (weak, nonatomic) IBOutlet UITextField *nameTextField;

@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;

@property (weak, nonatomic) IBOutlet UIButton *coverIconButton;

@property (weak, nonatomic) IBOutlet UIButton *homeIconButton;

@property (weak, nonatomic) IBOutlet UIButton *userInfoFirstButton;

@property (weak, nonatomic) IBOutlet UIButton *userInfoSecondButton;

@property (weak, nonatomic) IBOutlet UIButton *certFirstButton;

@property (weak, nonatomic) IBOutlet UIButton *cerSecondButton;

@end

@implementation MSBusinessUploadInfoController {
    UIButton *_selectIconButton; // 选择图片按钮
    NSMutableArray *_tempIconUrlList; // 选择图片URL数组
    NSInteger _selectIconIndex; // 当前选择的是第几张图片
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initData];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyBoard)];
    [self.scrollView addGestureRecognizer:tap];
}

- (void)initData {
    _tempIconUrlList = @[@"", @"", @"", @"", @"", @""].mutableCopy;
    _selectIconIndex = -1;
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSLog(@"点击了return按钮");
    if (textField == self.adreessTextField) {
        [self.titleTextField becomeFirstResponder];
    } else if (textField == self.titleTextField) {
        [self.nameTextField becomeFirstResponder];
    } else if (textField == self.nameTextField) {
        [self.phoneTextField becomeFirstResponder];
    } else if (textField == self.phoneTextField) {
        [self.view endEditing:YES];
    }
    return YES;
}

#pragma mark - TZImagePickerControllerDelegate

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    UIImage *image = [photos firstObject];
    // 获取凭证
    _WEAKSELF
    [MSUserCenterDataSource queryUploadImageConfigWithSuccess:^(NSDictionary * _Nonnull responseInfo) {
        if ([MSSafeObject isNull:responseInfo]) {
            return ;
        }
        [weakSelf handleImage:responseInfo image:image];
    } failure:^(NSError * _Nonnull error) {
        [MBProgressHUD showToastWithMessage:@"图像上传失败，请稍后再试！" toView:weakSelf.view];
    }];
}

- (void)handleImage:(NSDictionary *)response image:(UIImage *)image {
    _WEAKSELF
    [MBProgressHUD showMessage:@"图片上传中"];
    [MSUploadImageUtils uploadImage:image withImageUpload:response bucketName:@"" resultBlock:^(NSDictionary *responseInfo) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            if ([[MSSafeObject stringInfo:responseInfo[@"result"]] isEqualToString:@"1"]) {
                [weakSelf refreshIconListAndSelectButtonWithUploadImageSuccess:image imageUrl:[MSSafeObject stringInfo:responseInfo[@"photoname"]]];
            } else {
                [MBProgressHUD showToastWithMessage:@"图片上传失败！" toView:weakSelf.view];
            }
        });
    }];
}

#pragma mark - XIB Response

- (IBAction)backButtonClick:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)selectIconButtonClick:(UIButton *)sender {
    _selectIconButton = sender;
    _selectIconIndex = sender.tag - kBusinessIconButtonDefaultTag;
    [self presentSelectPhotoAlertController];
}

- (IBAction)uploadInfoButtonClick:(id)sender {
    // 判断输入框是否有内容
    if ([MSSafeObject isNull:self.adreessTextField.text]) {
        // 输入的地址为空
        [MBProgressHUD showToastWithMessage:@"店铺地址不能为空" toView:self.view];
        return;
    }
    if ([MSSafeObject isNull:self.titleTextField.text]) {
        // 输入的店铺名字为空
        [MBProgressHUD showToastWithMessage:@"店铺名称不能为空" toView:self.view];
        return;
    }
    if ([MSSafeObject isNull:self.nameTextField.text]) {
        // 联系人信息为空
        [MBProgressHUD showToastWithMessage:@"联系人信息不能为空" toView:self.view];
        return;
    }
    if ([MSSafeObject isNull:self.phoneTextField.text]) {
        // 联系人手机号码为空
        [MBProgressHUD showToastWithMessage:@"联系电话不能为空" toView:self.view];
        return;
    }
    // 判断是否已把所有的图片添加完毕
    NSInteger emptyUrlIndex = 0;
    for (NSString *iconUrl in _tempIconUrlList) {
        if ([MSSafeObject isNull:iconUrl]) {
            break;
        }
        emptyUrlIndex ++;
    }
    // 判断是否所有的IconURL都优质
    if (emptyUrlIndex < 6) {
        NSString *errorTip = @"";
        if (emptyUrlIndex == 0) {
            errorTip = @"请上传门店照片";
        } else if (emptyUrlIndex == 1) {
            errorTip = @"请上传店内环境照片";
        } else if (emptyUrlIndex == 1) {
            errorTip = @"请上传手持身份证正面照";
        } else if (emptyUrlIndex == 1) {
            errorTip = @"请上传手持身份证反面照";
        } else if (emptyUrlIndex == 1) {
            errorTip = @"请上传营业执照照片";
        } else if (emptyUrlIndex == 1) {
            errorTip = @"请上传经营许可证照片";
        }
        [MBProgressHUD showToastWithMessage:errorTip toView:self.view];
        return;
    }
    
    [MBProgressHUD showMessage:@"申请中..."];
    
    NSString *addressStr = [MSSafeObject stringInfo:self.adreessTextField];
    NSString *businessTitle = [MSSafeObject stringInfo:self.titleTextField.text];
    NSString *contactName = [MSSafeObject stringInfo:self.nameTextField.text];
    NSString *contactPhone = [MSSafeObject stringInfo:self.phoneTextField.text];
    _WEAKSELF
    [MSUserCenterDataSource applyForTenantsWithBusinessAddress:addressStr businessTitle:businessTitle contactName:contactName contactPhone:contactPhone uploadIconList:_tempIconUrlList.copy success:^(NSDictionary *responseInfo) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showToastWithMessage:@"申请成功，正在审核" toView:weakSelf.view];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        });        
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUD];
        NSString *errorMsg = error.localizedDescription?:@"申请商家入驻失败，请稍候重试";
        [MBProgressHUD showToastWithMessage:errorMsg toView:weakSelf.view];
    }];
}

#pragma mark - Event Response
/** 关闭键盘 */
- (void)closeKeyBoard {
    [self.view endEditing:YES];
}

#pragma mark - Private Method
/** 进入选择照片弹框 */
- (void)presentSelectPhotoAlertController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerVc.allowTakePicture = YES;
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = YES;
    //    imagePickerVc.allowPickingGif = YES;
    imagePickerVc.barItemTextColor = [UIColor blackColor];
    imagePickerVc.iconThemeColor = [UIColor orangeColor];
    imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
    imagePickerVc.oKButtonTitleColorDisabled = [UIColor blueColor];
    imagePickerVc.showSelectedIndex = YES;
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    imagePickerVc.cropRect = CGRectMake(0, (MS_SCREEN_HEIGHT - MS_SCREEN_WIDTH) / 2.0, MS_SCREEN_WIDTH, MS_SCREEN_WIDTH);
    [[UIViewController currentViewController] presentViewController:imagePickerVc animated:YES completion:nil];
}
/** 上传图片成功之后刷新图片列表和按钮 */
- (void)refreshIconListAndSelectButtonWithUploadImageSuccess:(UIImage *)selectImage imageUrl:(NSString *)imageUrl {
    [_selectIconButton setImage:selectImage forState:UIControlStateNormal];
    // 刷新数据源
    if (_tempIconUrlList.count > _selectIconIndex) {
        NSString *oldIconUrl = _tempIconUrlList[_selectIconIndex];
        if ([MSSafeObject isNull:oldIconUrl]) {
            _selectIconButton.layer.borderWidth = 1.0;
            _selectIconButton.layer.borderColor = [UIColor orangeColor].CGColor;
        }
        [_tempIconUrlList replaceObjectAtIndex:_selectIconIndex withObject:imageUrl];
    }
}


#pragma mark - Dealloc

- (void)dealloc {
    NSLog(@"%s", __func__);
}

@end
